package com.bestcem.xm.common.core.domain.web;

import com.bestcem.xm.common.core.enums.CommonErrorEnum;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;

/**
 * service 层返回结果封装类
 * 最后更新时间: 2021年6月4日15:05:55
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v1.0
 * @date 2021-05-08
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@ToString
@Setter
@Getter
public class XmViewResultJson<T> {

    private T data;

    private String msg;

    private Integer code;

    @JsonIgnore
    private boolean success;

    public static <T> XmViewResultJson<T> success() {
        return success(null, null);
    }

    public static <T> XmViewResultJson<T> success(T data) {
        return success(data, null);
    }

    public static <T> XmViewResultJson<T> success(T data, String msg) {
        XmViewResultJson<T> serviceResult = new XmViewResultJson<>();
        serviceResult.setData(data);
        serviceResult.setMsg(msg);
        serviceResult.setCode(0);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    public static <T> XmViewResultJson<T> fail(CommonErrorEnum errorEnum) {
        XmViewResultJson<T> serviceResult = new XmViewResultJson<>();
        serviceResult.setCode(errorEnum.getCode());
        serviceResult.setMsg(errorEnum.getMsg());
        serviceResult.setSuccess(Boolean.FALSE);
        return serviceResult;
    }

    public static <T> XmViewResultJson<T> fail(Integer code, String msg) {
        XmViewResultJson<T> serviceResult = new XmViewResultJson<>();
        serviceResult.setCode(code);
        serviceResult.setMsg(msg);
        serviceResult.setSuccess(Boolean.FALSE);
        return serviceResult;
    }

    public static <T> XmViewResultJson<T> fail(T data, Integer code, String msg) {
        XmViewResultJson<T> serviceResult = new XmViewResultJson<>();
        serviceResult.setData(data);
        serviceResult.setCode(code);
        serviceResult.setMsg(msg);
        serviceResult.setSuccess(Boolean.FALSE);
        return serviceResult;
    }

    public XmViewResultJson<T> setErrorCode(Integer code) {
        this.code = code;
        return this;
    }

    public static <T> XmViewResultJson<T> handleServiceResult(ServiceResult<T> serviceResult) {
        if (serviceResult.isSuccess()) {
            return XmViewResultJson.success(serviceResult.getData());
        } else {
            return XmViewResultJson.fail(-1, serviceResult.getMsg());
        }
    }
}

